﻿String.prototype.toDateTime = function () {
    try {
        return new Date(parseInt(this.replace("/Date(", "").replace(")/", ""), 10));
    } catch (err) { return null; }
};

var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);

var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);

Number.prototype.zf = function () {
    return this >= 10 ? String(this) : "0" + this;
};

Date.prototype.format = function (f) {
    if (!this.valueOf())
        return ' ';

    var d = this;

    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|h12|hh|nn|ss|a\/p)/gi,
        function ($1) {
            switch ($1.toLowerCase()) {
                case 'yyyy': return d.getFullYear();
                case 'mmmm': return gsMonthNames[d.getMonth()];
                case 'mmm': return gsMonthNames[d.getMonth()].substr(0, 3);
                case 'mm': return (d.getMonth() + 1).zf();
                case 'dddd': return gsDayNames[d.getDay()];
                case 'ddd': return gsDayNames[d.getDay()].substr(0, 3);
                case 'dd': return d.getDate().zf();
                case 'h12': return ((h = d.getHours() % 12) ? h : 12).zf();
                case 'hh': return d.getHours().zf();
                case 'nn': return d.getMinutes().zf();
                case 'ss': return d.getSeconds().zf();
                case 'a/p': return d.getHours() < 12 ? 'a' : 'p';
            }
        }
    );
};